package swingExtensions.list;

import io.github.jonestimd.swing.ButtonBarFactory;
import io.github.jonestimd.swing.list.BeanListModel;
import org.fluttercode.datafactory.impl.DataFactory;
import swingExtensions.demo.FrameDemo;
import swingExtensions.dialog.MessageDialogDemo;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;

public class BeanListModelDemo {

    private JList list;
    private BeanListModel<String> listModel;

    public JPanel createContentPanel() {
        listModel = new BeanListModel<>();
        DataFactory factory = new DataFactory();
        for (int i = 0; i < 10; i++) {
            listModel.addElement(factory.getFirstName());
        }

        list = new JList();
        list.setModel(listModel);

        ButtonBarFactory buttonBarFactory = new ButtonBarFactory();
        buttonBarFactory.add(new AbstractAction("增加") {
            @Override
            public void actionPerformed(ActionEvent e) {
                listModel.addElement(factory.getFirstName());
            }
        });
        buttonBarFactory.add(new AbstractAction("删除") {
            @Override
            public void actionPerformed(ActionEvent e) {
                listModel.removeElementAt(1);
            }
        });
        buttonBarFactory.add(new AbstractAction("清空") {
            @Override
            public void actionPerformed(ActionEvent e) {
                listModel.removeAll();
            }
        });
        buttonBarFactory.add(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                List<String> items = new ArrayList<>();
                for (int i = 0; i < 10; i++) {
                    items.add(factory.getFirstName());
                }
                listModel.setElements(items);
            }
        });

        JPanel panel = new JPanel(new BorderLayout());
        panel.add(new JScrollPane(list));
        panel.add(buttonBarFactory.get(), BorderLayout.SOUTH);
        return panel;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            BeanListModelDemo demo = new BeanListModelDemo();
            FrameDemo frameDemo = new FrameDemo(BeanListModelDemo.class.toString());
            frameDemo.setContentPane(demo.createContentPanel());
            frameDemo.setVisible(true);
        });
    }
}
